<?php
/**
 * 系統名稱: Lotto 系統
 * 檔案說明: 專案管理-修改
 * $Author$
 * $Id$
 *
 */

if (!defined("Gamble_lib_include")){
	define("Gamble_lib_include", 1);
	include_once(__Modules_Path."/LogRecord.lib.php");
	include_once(__Modules_Path."/Lotto.lib.php");

/**
 * 載入賠率
 * @param	intGID：操盤序號
 * @param	intLID：Lotto 種類序號
 * @param	intBType：下注種類序號
 * @param	intNum：號碼種類
 * @param	flOdds：賠率
 * @param	isAuto：是否自動操盤，0 -> 手動，1 -> 自動調整（押碼跳動），2 -> 代理
 * @param	strUserAccount：更改賠率人帳號
 * @return	 int -> 成功，false -> 失敗
 */
	function InsertBetTypeOdds($intGID, $intLID, $intBType, $intNum, $flOdds, $isAuto, $strUserAccount){
		global $_ConnMaster;
		if(empty($strUserAccount)){
			$GLOBALS["errormessage"] = "No Manage Data Error!!";
			$GLOBALS["errorhidden"] = "\nLine:".__LINE__."\nPage:".__FILE__;
			return false;
		}

		$strSQL = "insert into `bet_Odds`(`GambleID`,`LottoID`,`Bet_Type`,`Number`,`Odds`,`isAuto`,`AddDate`,`AddTime`,`UserAccount`,`OpIP`) values(".$intGID.",".$intLID.", ".$intBType.", ".$intNum.", '".$flOdds."', ".$isAuto.", CURRENT_DATE(), CURRENT_TIME(), '".$strUserAccount."','".getUserRemoteAdd()."')";
		if(!PMA_mysql_query($strSQL, $_ConnMaster)){
			$GLOBALS["errormessage"] = "Add Odds Data Error!!";
			$GLOBALS["errorhidden"] = "Error: ".PMA_mysql_error($_ConnMaster)."\nSQL:".$strSQL."\nLine:".__LINE__."\nPage:".__FILE__;
			@mail("pinus@uuss.net", $GLOBALS["errormessage"].$_SERVER["HTTP_HOST"], $GLOBALS["errorhidden"], "From:".$_SERVER["HTTP_HOST"]."<apache@secure.uuss.net>");
			return false;
		}

		return mysql_insert_id($_ConnMaster);
	}

/**
 * 載入賠率事件
 * @param	intGID：操盤序號
 * @param	intLID：Lotto 種類序號
 * @param	intBType：下注種類序號
 * @param	strMemo：事件
 * @param	isAuto：是否自動操盤，0 -> 手動，1 -> 自動調整（押碼跳動），2 -> 代理
 * @param	strUserAccount：更改賠率人帳號
 * @return	 int -> 成功，false -> 失敗
 */
	function InsertEvenOdds($intGID, $intLID, $intBType, $strMemo, $strUserAccount){
		global $_ConnMaster;
		if(empty($strUserAccount)){
			$GLOBALS["errormessage"] = "No Manage Data Error!!";
			$GLOBALS["errorhidden"] = "\nLine:".__LINE__."\nPage:".__FILE__;
			return false;
		}

		$strSQL = "insert into `bet_Odds`(`GambleID`,`LottoID`,`Bet_Type`,`Memo`,`AddDate`,`AddTime`,`UserAccount`,`OpIP`) values(".$intGID.", ".$intLID.", ".$intBType.", '".$strMemo."', CURRENT_DATE(), CURRENT_TIME(), '".$strUserAccount."','".getUserRemoteAdd()."')";
		if(!PMA_mysql_query($strSQL, $_ConnMaster)){
			$GLOBALS["errormessage"] = "Add Odds Data Error!!";
			$GLOBALS["errorhidden"] = "Error: ".PMA_mysql_error($_ConnMaster)."\nSQL:".$strSQL."\nLine:".__LINE__."\nPage:".__FILE__;
			return false;
		}

		return mysql_insert_id($_ConnMaster);
	}


/**
 * 批次載入賠率
 * @param	intLID 樂透序號
 * @param	intGID 操盤序號
 * @param	arrOdds 賠率 values 陣列
 * @return	回傳 true -> 成功，false -> 失敗
 */
	function setMultiAddOdds($intLID, $intGID, $arrOdds){
		global $_ConnMaster;

		if(sizeof($arrOdds) == 0)return true;

		$strOSQL = "(".$intGID.",".$intLID.", %d, %d, '%s', 0, CURRENT_DATE(), CURRENT_TIME(), '".$_SESSION["Admin_Info"] -> Account."','".getUserRemoteAdd()."')";
		$arrOSQL = array();
		foreach($arrOdds as $arrO){
			$arrOSQL[] = sprintf($strOSQL, $arrO[0], $arrO[1], $arrO[2]);
			if(sizeof($arrOSQL) > 2000){
				$strSQL = "insert into `bet_Odds`(`GambleID`,`LottoID`,`Bet_Type`,`Number`,`Odds`,`isAuto`,`AddDate`,`AddTime`,`UserAccount`,`OpIP`) values".implode(", ", $arrOSQL);

				if(!PMA_mysql_query($strSQL, $_ConnMaster)){
					$GLOBALS["errormessage"] = "Add Odds Data Error!!";
					$GLOBALS["errorhidden"] = "Error: ".PMA_mysql_error($_ConnMaster)."\nSQL:".$strSQL."\nLine:".__LINE__."\nPage:".__FILE__;
					return false;
				}
				$arrOSQL = array();
			}
		}

		$strSQL = "insert into `bet_Odds`(`GambleID`,`LottoID`,`Bet_Type`,`Number`,`Odds`,`isAuto`,`AddDate`,`AddTime`,`UserAccount`,`OpIP`) values".implode(", ", $arrOSQL);

		if(!PMA_mysql_query($strSQL, $_ConnMaster)){
			$GLOBALS["errormessage"] = "Add Odds Data Error!!";
			$GLOBALS["errorhidden"] = "Error: ".PMA_mysql_error($_ConnMaster)."\nSQL:".$strSQL."\nLine:".__LINE__."\nPage:".__FILE__;
			return false;
		}

		return true;
	}


/**
 * 初始化 TodayGame
 * @param	intLID 樂透序號
 * @param	intGID 操盤序號
 * @return	回傳 true -> 成功，false -> 失敗
 */
	function initialTodayGame($intLID, $intGID){
		global $_ConnMaster;

		$strSQL = "insert into `bet_TodayGame%d`(`GambleID`, `LottoID`, `Bet_Type`, `Number`, `OddsID`, `Odds`) (select `GambleID`, `LottoID`, `Bet_Type`, `Number`, `ID`, `Odds` from `bet_Odds` where `GambleID` = %d and `LottoID` = %d order by `ID`) ON DUPLICATE KEY UPDATE `OddsID` = VALUES(`OddsID`), `Odds` = VALUES(`Odds`)";
		$strSQL = sprintf($strSQL, $intLID, $intGID, $intLID);

		if(!PMA_mysql_query($strSQL, $_ConnMaster)){
			$GLOBALS["errormessage"] = "Initial TodayGame Data Error!!";
			$GLOBALS["errorhidden"] = "Error: ".PMA_mysql_error($_ConnMaster)."\nSQL:".$strSQL."\nLine:".__LINE__."\nPage:".__FILE__;
			return false;
		}

		return true;
	}


/**
 * 更改 bet_TodayGame 資料表狀態
 * @param	intGID：操盤序號
 * @param	intLID：Lotto 種類序號
 * @param	intBType：下注種類序號
 * @param	intNum：號碼種類
 * @param	intOID：賠率序號
 * @param	flOdds：賠率
 * @param	strOhterCase：其他要更改條件，", xx = yy, ....."
 * @return	 true -> 成功，false -> 失敗
 */
	function UpdateTodayGame($intGID, $intLID, $intBType, $intNum, $intOID, $flOdds, $strOhterCase = ""){
		global $_ConnMaster;

		$strSQL = "update `bet_TodayGame".$intLID."` set `OddsID` = ".$intOID.", `Odds` = ".$flOdds.$strOhterCase.", `UpdateTime` = UNIX_TIMESTAMP() where `GambleID` = ".$intGID." and `LottoID` = ".$intLID." and  `Bet_Type` = ".$intBType." and `Number` = ".$intNum;

		if(!PMA_mysql_query($strSQL, $_ConnMaster)){
			$GLOBALS["errormessage"] = "Update TodayGame Data Error!!";
			$GLOBALS["errorhidden"] = "Error: ".PMA_mysql_error($_ConnMaster)."\nSQL:".$strSQL."\nLine:".__LINE__."\nPage:".__FILE__;
			return false;
		}

		if(mysql_affected_rows($_ConnMaster) == 0){
			$strSQL = "insert into `bet_TodayGame".$intLID."`(`GambleID`, `LottoID`, `Bet_Type`, `Number`, `OddsID`, `Odds`) values(".$intGID.",".$intLID.",".$intBType.",".$intNum.",".$intOID.",".$flOdds.")";
			if(!PMA_mysql_query($strSQL, $_ConnMaster)){
				$GLOBALS["errormessage"] = "Update TodayGame Data Error!!";
				$GLOBALS["errorhidden"] = "Error: ".PMA_mysql_error($_ConnMaster)."\nLine:".__LINE__."\nPage:".__FILE__;
				return false;
			}
		}
		return true;
	}

/**
 * 更改 bet_TodayGame 資料表 OhterCase 狀態
 * @param	intGID：操盤序號
 * @param	intLID：Lotto 種類序號
 * @param	intBType：下注種類序號
 * @param	intNum：號碼種類
 * @param	strOhterCase：其他要更改條件，", xx = yy, ....."
 * @return	 true -> 成功，false -> 失敗
 */
	function UpdateTodayGameOhterCase($intGID, $intLID, $intBType, $intNum, $strOhterCase){
		global $_ConnMaster;

		$strSQL = "update `bet_TodayGame".$intLID."` set ".$strOhterCase.", `UpdateTime` = UNIX_TIMESTAMP() where `GambleID` = ".$intGID." and `LottoID` = ".$intLID." and  `Bet_Type` = ".$intBType." and `Number` = ".$intNum;
		if(!PMA_mysql_query($strSQL, $_ConnMaster)){
			$GLOBALS["errormessage"] = "Update TodayGame Data Error!!";
			$GLOBALS["errorhidden"] = "Error: ".PMA_mysql_error($_ConnMaster)."\nSQL:".$strSQL."\nLine:".__LINE__."\nPage:".__FILE__;
			return false;
		}
		return true;
	}

/**
 * 停押 bet_TodayGame 資料表
 * @param	intGID 操盤序號
 * @param	intLID 樂透序號
 * @param	intBType 下注種類序號
 * @param	intLType 樂透分類序號
 * @param	intStopBet：停押或開放，0 -> 開放，1 -> 停押
 * @param	strNum：號碼種類字串，1,4,..,n
 * @return	 true -> 成功，false -> 失敗
 */
	function StopBetTodayGame($intGID, $intLID, $intBType, $intLType, $intStopBet, $strNum){
		global $_ConnMaster;

		$strBType = (string)$intBType;
		if($intLType == 1 && ($intBType == 1 || $intBType == 28))$strBType = "1, 28";

		$strSQL = "update `bet_TodayGame".$intLID."` set `isStopBet` = ".$intStopBet.", `UpdateTime` = UNIX_TIMESTAMP() where `GambleID` = ".$intGID." and `Bet_Type` in (".$strBType.")";
		if($strNum != "all")$strSQL .= " and `Number` in (".$strNum.")";
		if(!PMA_mysql_query($strSQL, $_ConnMaster)){
			$GLOBALS["errormessage"] = "Update TodayGame Data Error!!";
			$GLOBALS["errorhidden"] = "Error: ".PMA_mysql_error($_ConnMaster)."\nSQL:".$strSQL."\nLine:".__LINE__."\nPage:".__FILE__;
			return false;
		}
		$strMemo = "S-".(string)$intGID."-".(string)$intBType."-".$strNum."-".(string)$intStopBet;
		if(!InsertEvenOdds($intGID, $intLID, -2, $strMemo, $_SESSION["Admin_Info"] -> Account))return false;

		//產生 TodayGame File
		if(!MakeTodayGameFile($intLID, $intBType))return false;
		if($intLType == 1 && ($intBType == 1 || $intBType == 28))if(!MakeTodayGameFile($intLID, ($intBType == 1?28:1)))return false;
		return true;
	}

/**
 * 停押所有 bet_TodayGame 資料表
 * @param	intGID 操盤序號
 * @param	intLID 樂透序號
 * @param	intBType 下注種類序號
 * @param	intLType 樂透分類序號
 * @param	intStopBet 停押或開放，0 -> 開放，1 -> 停押
 * @param	strNum 號碼種類字串，1,4,..,n
 * @return	 true -> 成功，false -> 失敗
 */
	function StopAllBetTodayGame($intGID, $intLID, $strBType, $intLType, $intStopBet, $strNum){
		$arrBetType = explode(",", $strBType);

		foreach($arrBetType as $intBT){
			if(!StopBetTodayGame($intGID, $intLID, $intBT, $intLType, $intStopBet, "all"))return false;
		}
		return true;
	}


/**
 * 依 Number 取得賠率資料
 * @param	intLID Lotto 種類序號
 * @param	intGID 操盤序號
 * @param	intBT 下注種類序號
 * @param	strNum 號碼
 * @return	 true -> array，false -> 失敗
 */
	function getTodayGameDataForMultiNumber($intLID, $intGID, $intBT, $strNum){
		global $_Conn, $$_Conn;

		$strSQL = "select `GambleID`, `LottoID`, `Bet_Type`, `Number`, `OddsID`, `Odds`, `isStopBet` from `bet_TodayGame".$intLID."` where `LottoID` = ".$intLID." and `GambleID` = ".$intGID." and `Bet_Type` = ".$intBT." and `Number` in (".$strNum.")";
		if(!$RS = PMA_mysql_query($strSQL, $$_Conn)){
			$GLOBALS["errormessage"] = "Find TodayGame Data Error!!";
			$GLOBALS["errorhidden"] = "Error: ".PMA_mysql_error($$_Conn)."\nSQL:".$strSQL."\nLine:".__LINE__."\nPage:".__FILE__;
			return false;
		}

		$arrTodayGame = array();
		while($Rows = PMA_mysql_fetch_array($RS, MYSQL_ASSOC)){
			$arrTodayGame[$intBT][$Rows["Number"]] = $Rows;
		}
		return $arrTodayGame;
	}

/**
 * 產生 TodayGame 檔案
 * @param	intLID：Lotto 種類序號
 * @param	intBType：下注種類序號
 * @return	 true -> 成功，false -> 失敗
 * 產生檔案 /common/todaygame/TodayGame?x_?y.inc.php
 * ?x -> Lotto 種類序號，?y -> 下注種類序號
 */
	function MakeTodayGameFile($intLID, $intBType){
		global $_Conn, $$_Conn;
		if($intLID == 4 && $intBType >= 7 && $intBType <= 11)return true;

		$_strLockFile = __Common_Path."/todaygame/lock.today".$intLID."_".$intBType;
		while (!@mkdir($_strLockFile, 0755)) {
			if($i < 15){
				$i++;
				usleep(300);
			}else{
				@rmdir($_strLockFile);
			}
		}

		$strSQL = "select `GambleID`, `LottoID`, `Bet_Type`, `Number`, `OddsID`, `Odds`, `isStopBet` from `bet_TodayGame".$intLID."` where `LottoID` = ".$intLID." and `Bet_Type` = ".$intBType;
		if(!$RS = PMA_mysql_query($strSQL, $$_Conn)){
			$GLOBALS["errormessage"] = "Find TodayGame Data Error!!";
			$GLOBALS["errorhidden"] = "Error: ".PMA_mysql_error($$_Conn)."\nSQL:".$strSQL."\nLine:".__LINE__."\nPage:".__FILE__;
			@rmdir($_strLockFile);
			return false;
		}

		while($Rows = PMA_mysql_fetch_array($RS, MYSQL_ASSOC)){
			$arrFName = array();
			while(list($k, $v) = each($Rows)){
				$arrFName[] = "\"".$k."\"=>\"".$v."\"";
			}
			$_strCon .= "$"."_arrTodayGame[".$Rows["GambleID"]."][".$intBType."][".$Rows["Number"]."]=array(".join(",", $arrFName).");\n";
		}

		$strCon = "<"."?"."php\n".$_strCon."?".">";
		$strFile = __Common_Path."/todaygame/TodayGame".$intLID."_".$intBType.".inc.php";
		if(!writeFile($strFile, $strCon, "w"))return false;

		@rmdir($_strLockFile);
		return true;
	}

/**
 * 刪除以結束在 bet_TodayGame 該期樂透資料
 * @param	intGID：操盤序號
 * @param	intLID：樂透種類序號
 * @return	 true -> 成功，false -> 失敗
 */
	function DeleteTodayGame($intGID, $intLID){
		global $_ConnMaster;

		$strSQL = "delete from `bet_TodayGame".$intLID."` where `LottoID` = ".$intLID;//GambleID = ".$intGID." and 
		if(!PMA_mysql_query($strSQL, $_ConnMaster)){
			$GLOBALS["errormessage"] = "Delete TodayGame Data Error!!";
			$GLOBALS["errorhidden"] = "Error: ".PMA_mysql_error($_ConnMaster)."\nLine:".__LINE__."\nPage:".__FILE__;
			return false;
		}

		$strSQL = "select a.ID as ID from `bet_BetType` a, `bet_Lotto` b where a.isOff = 0 and a.LType = b.LType and b.ID = '".$intLID."'";
		if(!$RS = PMA_mysql_query($strSQL, $_ConnMaster)){
			$GLOBALS["errormessage"] = "Find BetType Data Error!!";
			$GLOBALS["errorhidden"] = "Error: ".PMA_mysql_error($_ConnMaster)."\nLine:".__LINE__."\nPage:".__FILE__;
			return false;
		}

		while($Rows = PMA_mysql_fetch_object($RS)){
			//產生 TodayGame File
			if(!MakeTodayGameFile($intLID, $Rows -> ID))return false;
		}
		return true;
	}  //  DeleteTodayGame()  //


/**
 * 取得今日以後最早新增的 Gamble 陣列資料
 * @param	intLID：Lotto 種類序號
 * @param	isEnd：是否已經結帳
 * @return	 Array -> 成功，false -> 失敗
 */
	function getNewGambleData($intLID, $isEnd){
		if($isEnd == 1){
			return getOneGambleData('', (string)$intLID, (string)$isEnd, true, 'order by ID desc');
		}else{
			return getOneGambleData('', (string)$intLID, (string)$isEnd, true, 'order by ID');
		}
	}

/**
 * 依照 ID 取得 Gamble 陣列資料
 * @param	strGID：Gamble序號
 * @return	 Array -> 成功，false -> 失敗
 */
	function getGambleDataByID($strGID){
		return getOneGambleData((string)$strGID, '', '', '', '');
	}

/**
 * 依照 最後一場 Gamble 陣列資料
 * @param	intLID：Lotto 種類序號
 * @return	 Array -> 成功，false -> 失敗
 */
	function getLastOneGambleData($intLID){
		return getOneGambleData('', (string)$intLID, '', '', 'order by ID desc');
	}

/**
 * 取得單一 Gamble 陣列資料
 * @param	strGID：Gamble序號
 * @param	strLID：Lotto 種類序號
 * @param	isEnd：是否已經結帳
 * @param	isToday：是否今日以後
 * @param	strOrderBy：排序欄位
 * @return	 Array -> 成功，false -> 失敗
 */
	function getOneGambleData($strGID, $strLID, $isEnd, $isToday, $strOrderBy){
		global $_Conn, $$_Conn;

		$strSQL = "select * from `bet_Gamble` where 1";
		if($strGID != "")$strSQL .= " and ID in (".$strGID.")";
		if($strLID != "")$strSQL .= " and LottoID = ".$strLID;
		if($isEnd !== "")$strSQL .= " and isEnd = ".$isEnd;
		if($isToday == 1 || $isToday === true)$strSQL .= " and GameDate >= CURRENT_DATE()";
		$strSQL .= " ".$strOrderBy." limit 0, 1";
		//print $strSQL;
		if(!$RS = PMA_mysql_query($strSQL, $$_Conn)){
			$GLOBALS["errormessage"] = "Find Gamble Data Error!!";
			$GLOBALS["errorhidden"] = "Error: ".PMA_mysql_error($$_Conn)."\nLine:".__LINE__."\nPage:".__FILE__;
			return false;
		}

		if(PMA_mysql_num_rows($RS) == 0)return array();
		return PMA_mysql_fetch_array($RS, MYSQL_ASSOC);
	}

/**
 * 取得多筆 Gamble 陣列資料
 * @param	strGID：Gamble序號
 * @param	strLID：Lotto 種類序號
 * @param	isEnd：是否已經結帳
 * @param	isToday：是否今日以後
 * @param	strOrderBy：排序欄位
 * @return	 Array -> 成功，false -> 失敗
 */
	function getMoreGambleData($strGID, $strLID, $isEnd, $isToday, $strOrderBy){
		global $_Conn, $$_Conn;

		$strSQL = "select * from `bet_Gamble` where 1";
		if($strGID != "")$strSQL .= " and ID in (".$strGID.")";
		if($strLID != "")$strSQL .= " and LottoID = ".$strLID;
		if($isEnd !== "")$strSQL .= " and isEnd = ".$isEnd;
		if($isToday == 1 || $isToday === true)$strSQL .= " and GameDate >= CURRENT_DATE()";
		$strSQL .= " ".$strOrderBy." ";
		//print $strSQL;
		if(!$RS = PMA_mysql_query($strSQL, $$_Conn)){
			$GLOBALS["errormessage"] = "Find Gamble Data Error!!";
			$GLOBALS["errorhidden"] = "Error: ".PMA_mysql_error($$_Conn)."\nLine:".__LINE__."\nPage:".__FILE__;
			return false;
		}

		$arrGame = array();
		if(PMA_mysql_num_rows($RS) == 0)return $arrGame;
		while($arrG = PMA_mysql_fetch_array($RS, MYSQL_ASSOC)){
			 $arrGame[$arrG["ID"]] = $arrG;
		}
		return $arrGame;
	}
//-------------------------------------------------------//
//Gamble_lib End
}
?>